<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { useProductsStore } from '../stores/products'

const route = useRoute()
const productsStore = useProductsStore()

// 搜索和筛选状态
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('default')
const currentPage = ref(1)
const productsPerPage = 8

// 从路由参数初始化分类筛选
watch(() => route.query.category, (newCategory) => {
  selectedCategory.value = newCategory || ''
  currentPage.value = 1
}, { immediate: true })

// 计算筛选和排序后的商品列表
const filteredProducts = computed(() => {
  let products = [...productsStore.products]
  
  // 关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    products = products.filter(product => 
      product.name.toLowerCase().includes(query) ||
      product.description.toLowerCase().includes(query)
    )
  }
  
  // 分类筛选
  if (selectedCategory.value) {
    products = products.filter(product => product.categoryId === selectedCategory.value)
  }
  
  // 排序
  switch (sortBy.value) {
    case 'price-asc':
      products.sort((a, b) => a.price - b.price)
      break
    case 'price-desc':
      products.sort((a, b) => b.price - a.price)
      break
    case 'sales':
      products.sort((a, b) => b.sales - a.sales)
      break
    case 'rating':
      products.sort((a, b) => b.rating - a.rating)
      break
    default:
      // 默认排序（新品优先）
      products.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
  }
  
  return products
})

// 分页商品
const paginatedProducts = computed(() => {
  const startIndex = (currentPage.value - 1) * productsPerPage
  return filteredProducts.value.slice(startIndex, startIndex + productsPerPage)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredProducts.value.length / productsPerPage)
})

// 获取分类数据
const categories = computed(() => productsStore.categories)

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  sortBy.value = 'default'
  currentPage.value = 1
}

// 切换到指定页
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 加载数据
onMounted(() => {
  if (productsStore.products.length === 0) {
    productsStore.loadProducts()
  }
})
</script>

<template>
  <main class="products-container">
    <div class="container">
      <h1 class="page-title">商品列表</h1>
      
      <div class="products-content">
        <!-- 筛选侧边栏 -->
        <aside class="filter-sidebar">
          <div class="filter-section">
            <h3 class="filter-title">搜索商品</h3>
            <div class="search-box">
              <input
                type="text"
                v-model="searchQuery"
                placeholder="搜索商品名称或描述..."
                class="search-input"
                @input="currentPage = 1"
              />
              <button class="search-button">🔍</button>
            </div>
          </div>
          
          <div class="filter-section">
            <h3 class="filter-title">商品分类</h3>
            <div class="category-filters">
              <label class="filter-option">
                <input
                  type="radio"
                  name="category"
                  :value="''"
                  v-model="selectedCategory"
                  @change="currentPage = 1"
                />
                <span>全部分类</span>
              </label>
              <label 
                v-for="category in categories" 
                :key="category.id"
                class="filter-option"
              >
                <input
                  type="radio"
                  name="category"
                  :value="category.id"
                  v-model="selectedCategory"
                  @change="currentPage = 1"
                />
                <span>{{ category.name }}</span>
              </label>
            </div>
          </div>
          
          <div class="filter-section">
            <h3 class="filter-title">排序方式</h3>
            <select 
              v-model="sortBy" 
              class="sort-select"
              @change="currentPage = 1"
            >
              <option value="default">默认排序</option>
              <option value="price-asc">价格从低到高</option>
              <option value="price-desc">价格从高到低</option>
              <option value="sales">销量优先</option>
              <option value="rating">评分优先</option>
            </select>
          </div>
          
          <button class="reset-filters" @click="resetFilters">重置筛选</button>
        </aside>
        
        <!-- 商品列表 -->
        <div class="products-main">
          <!-- 筛选结果信息 -->
          <div class="results-info">
            <p>找到 {{ filteredProducts.length }} 个商品</p>
          </div>
          
          <!-- 商品网格 -->
          <div v-if="paginatedProducts.length > 0" class="products-grid">
            <div v-for="product in paginatedProducts" :key="product.id" class="product-card">
              <RouterLink :to="`/products/${product.id}`" class="product-link">
                <div class="product-image-wrapper">
                  <img :src="product.image" :alt="product.name" class="product-image" />
                  <span v-if="product.discount" class="discount-badge">{{ product.discount }}</span>
                </div>
                <div class="product-info">
                  <h3 class="product-name">{{ product.name }}</h3>
                  <div class="product-rating">
                    <span class="rating-stars">⭐</span>
                    <span class="rating-value">{{ product.rating }}</span>
                    <span class="rating-count">({{ product.reviewCount }})</span>
                  </div>
                  <div class="product-price">
                    <span class="current-price">¥{{ product.price }}</span>
                    <span class="original-price">¥{{ product.originalPrice }}</span>
                  </div>
                  <div class="product-sales">已售 {{ product.sales }}</div>
                </div>
              </RouterLink>
            </div>
          </div>
          
          <!-- 无结果提示 -->
          <div v-else class="no-results">
            <div class="no-results-icon">📦</div>
            <h3>没有找到相关商品</h3>
            <p>请尝试调整筛选条件或搜索关键词</p>
            <button class="reset-btn" @click="resetFilters">重置筛选</button>
          </div>
          
          <!-- 分页 -->
          <div v-if="totalPages > 1" class="pagination">
            <button 
              class="pagination-btn"
              :disabled="currentPage === 1"
              @click="goToPage(currentPage - 1)"
            >
              ← 上一页
            </button>
            
            <div class="page-numbers">
              <button
                v-for="page in totalPages"
                :key="page"
                class="page-btn"
                :class="{ active: page === currentPage }"
                @click="goToPage(page)"
              >
                {{ page }}
              </button>
            </div>
            
            <button 
              class="pagination-btn"
              :disabled="currentPage === totalPages"
              @click="goToPage(currentPage + 1)"
            >
              下一页 →
            </button>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
.products-container {
  min-height: calc(100vh - 130px);
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin-bottom: 40px;
  text-align: center;
}

.products-content {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 30px;
}

/* 筛选侧边栏样式 */
.filter-sidebar {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  height: fit-content;
  position: sticky;
  top: 20px;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

/* 搜索框样式 */
.search-box {
  position: relative;
}

.search-input {
  width: 100%;
  padding: 12px 16px;
  padding-right: 40px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #4285f4;
}

.search-button {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
  padding: 8px;
}

/* 分类筛选样式 */
.category-filters {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-option {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.filter-option:hover {
  background-color: #f5f5f5;
}

.filter-option input[type="radio"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.filter-option span {
  font-size: 16px;
  color: #333;
}

/* 排序选择样式 */
.sort-select {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  background-color: #fff;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.sort-select:focus {
  outline: none;
  border-color: #4285f4;
}

/* 重置按钮样式 */
.reset-filters {
  width: 100%;
  padding: 12px;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reset-filters:hover {
  background-color: #ff3838;
}

/* 商品主内容区域样式 */
.products-main {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.results-info {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.results-info p {
  font-size: 16px;
  color: #666;
}

/* 商品网格样式 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.product-card {
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.product-link {
  text-decoration: none;
  display: block;
}

.product-image-wrapper {
  position: relative;
  height: 240px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.discount-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background-color: #ff4757;
  color: #fff;
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  height: 48px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.rating-stars {
  color: #ffb400;
}

.rating-value {
  font-weight: 600;
  color: #333;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.current-price {
  font-size: 20px;
  font-weight: 700;
  color: #ff4757;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

/* 无结果样式 */
.no-results {
  text-align: center;
  padding: 60px 20px;
}

.no-results-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.no-results h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 12px;
}

.no-results p {
  font-size: 16px;
  color: #666;
  margin-bottom: 24px;
}

.reset-btn {
  padding: 12px 24px;
  background-color: #4285f4;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reset-btn:hover {
  background-color: #3367d6;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 40px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.pagination-btn {
  padding: 10px 16px;
  background-color: #f9f9f9;
  color: #333;
  border: 1px solid #e9e9e9;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f0f0f0;
  border-color: #d9d9d9;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 8px;
}

.page-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #e9e9e9;
  border-radius: 6px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover {
  background-color: #f9f9f9;
  color: #333;
  border-color: #d9d9d9;
}

.page-btn.active {
  background-color: #fff;
  color: #333;
  border-color: #333;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .products-content {
    grid-template-columns: 260px 1fr;
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .products-content {
    grid-template-columns: 1fr;
  }
  
  .filter-sidebar {
    position: static;
    margin-bottom: 24px;
  }
  
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
  
  .product-image-wrapper {
    height: 200px;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .page-numbers {
    overflow-x: auto;
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .products-grid {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .container {
    padding: 0 15px;
  }
}
</style>